/**
 * Created by John on 10/10/2014.
 */
public class DoubleLinkedList {
	Node head;
	int size = 0;

    class Node {
        int value;
        Node next;
        Node prev;

        Node(int value) {
            this.next = null;
            this.prev = null;
            this.value = value;
	        size++;
        }
    }

	public int size() {
		return size;
	}

    public void addToStart(int value) {
       Node temp = new Node(value);
       addToStart(temp);
    }

    public void addToStart(Node temp) {
        if(head == null) {
            head = temp;
        } else {
            temp.next = head;
            head.prev = temp;
            head = temp;
        }
	    size++;
    }

	public void addToEnd(int value) {
		Node node = new Node(value);
		addToEnd(node);
	}

	public void addToEnd(Node node) {
		if(head == null) {
			addToStart(node);
		} else {
			Node temp = head;
			for( ;temp.next != null; temp = temp.next );
				temp.next = node;
				node.prev = temp;
		}
		size++;
	}

	public void addToPos(int value, int pos) throws Exception {
		Node node = new Node(value);
		addToPos(node, pos);
	}

    public void addToPos(Node node, int pos) throws Exception {
		try {
			if(head == null || pos == 0) {
				addToStart(node);
			} else {
				Node temp = head;
				for(int i = 2; i <= pos; i++) {
					temp = temp.next;
				}
				node.next = temp.next;
				temp.next = node;
				node.prev = temp;
				size++;
			}
		} catch(Exception e) {
			System.out.println("Wrong pos for inserting!");
		}
    }

	public void deleteFromStart() {
		if(head == null) {
			System.out.println("Nothing to delete!");
		} else {
			head = head.next;
		}
		size--;
	}

	public void deleteFromEnd() {
		Node tmp = head;

		if( head != null ) {
			while(tmp.next != null ) {
				tmp = tmp.next;
			}
			tmp.prev.next = null;
			tmp = null;
		}
		size--;
	}

	public void deleteFromPosition(int pos) throws Exception{
		Node tmp = head;
		if(pos >= 0) {
			try {
				if(pos == 0) {
					deleteFromStart();
				} else {
					while(pos > 0 && pos < size) {
						tmp = tmp.next;
						pos--;
					}
					tmp.prev.next = tmp.next;
					tmp.next = tmp.prev;
					size--;
				}
			} catch(Exception e) {
				System.out.println("Wrong pos for deletion!");
				e.printStackTrace();
			}
		}
	}

	public void printReverse() {
		Node tmp = head;

		while(tmp.next != null) {
			tmp = tmp.next;
		}

		while(tmp.prev != null) {
			System.out.print(tmp.value);
			tmp = tmp.prev;
		}
	}

    public void printList() {
        Node temp = head;

        for( ;temp != null; temp = temp.next ) {
            System.out.print(temp.value);
        }
	    System.out.println("\n");
    }
}


